import { useData } from "@sker/runtime"
import { HttpError, toSuccess, useTransaction } from "@sker/core"
import { z } from "zod"
import { WxToken } from "@sker/entities"
import dayjs from "dayjs"

/**
 * 刷新登录token
 */
export default async () => {
    const input = z.object({
        refresh_token: z.string()
    })
    const body = input.parse(useData())
    await useTransaction(async m => {
        const wxToken = await m.findOne(WxToken, { where: { refresh_token: body.refresh_token }, select: { id: true, expires_in: true, refresh_token_expires_in: true } })
        if (!wxToken) throw new HttpError(`refresh token error`)
        await m.update(WxToken, wxToken.id, {
            expires_in: dayjs().add(30, 'day').toDate(),
            refresh_token_expires_in: dayjs().add(365, 'day').toDate()
        })
    })
    return toSuccess(true)
}
